const jwt = require('jsonwebtoken')
const { promisify } = require('util')

const toJwt = promisify(jwt.sign)
const verify = promisify(jwt.verify)
// const logger = require('./logger')

// 生成token
const createToken = async (info) => {
  return await toJwt({ info }, 'dyxw-token', { expiresIn: '15d' })
}

// 验证token
const verifyToken = async (request, reply, done) => {
  const token = request.headers['authorization']
  if (!token) {
    return reply.status(401).send({
      code: reply.statusCode,
      data: null,
      message: 'Token 不能为空！',
    })
  }
  const _token = token ? token.split('Bearer ')[1] : null

  const { info } = await verify(_token, 'dyxw-token')
  if (!info) {
    return reply.status(401).send({
      code: reply.statusCode,
      data: 'Invalid token',
      message: 'Token 认证失败！请重新登陆！',
    })
  }
  if (request.method === 'POST') {
    if (request.body) {
      request.body = {
        ...request.body,
        ...info,
      }
    } else {
      request.body = {
        ...request.body,
        ...info,
      }
    }
  } else {
    request.query = {
      ...info,
      ...request.query,
    }
  }

  // logger.info(`
  //   登陆人：${JSON.stringify(info)}
  //   请求地址：${request.url}
  //   `)
  return
}

module.exports = {
  createToken,
  verifyToken,
}
